package com.ytktt.study.week7.task2.gen.id;

/**
 * 雪花算法
 *
 * @author ytk
 */
public class Snowflake {

    private final long workerId;
    private final long dataCenterId;

    private long sequence = 0L;

    private long twepoch = 1288834974657L;

    private final long workerIdBits = 5L;
    private final long dataCenterIdBits = 5L;
    private final long maxWorkerId = ~(-1L << this.workerIdBits);
    private final long maxDataCenterId = ~(-1L << this.dataCenterIdBits);
    private final long sequenceBits = 12L;

    private final long workerIdShift = this.sequenceBits;
    private final long dataCenterIdShift = this.workerIdShift + this.workerIdBits;
    private final long timestampsShift = this.dataCenterIdShift + this.dataCenterIdBits;
    private final long maxSequence = ~(-1L << sequenceBits);

    private long lastTimestamp = 1L;

    public Snowflake(long workerId, long dataCenterId) {
        if ((workerId > this.maxWorkerId || workerId < 0) ||
                (dataCenterId > this.maxDataCenterId || dataCenterId < 0)) {
            throw new IllegalArgumentException("invalid workerId/dataCenterId");
        }
        this.workerId = workerId;
        this.dataCenterId = dataCenterId;
    }

    public synchronized long nextId() {
        long timestamp = System.currentTimeMillis();
        if (timestamp < this.lastTimestamp) {
            throw new RuntimeException("时钟回调");
        }

        // 如果此次生成id的时间戳与上一次生成id的时间戳相同，则通过机器码与序列号区分id值
        if (this.lastTimestamp == timestamp) {
            // 通过位运算保证sequence不会超出序列号锁能容纳的最大值
            // 例如，当前sequence最大值为4095，再加1就会使sequence恢复到0
            // 如果sequence为0，就表示sequence已满
            this.sequence = (this.sequence + 1) & this.maxSequence;
            // 如果sequence已满，则去偷下一个时间的
            if (this.sequence == 0) {
                timestamp = this.nextMills(this.lastTimestamp);
            }
        } else {
            // 如果此次生成id的时间戳与上一次的时间戳不同，则sequence重新开始
            this.sequence = 0;
        }
        // 更新最近一次生成id的时间戳
        this.lastTimestamp = timestamp;

        return ((timestamp - this.twepoch) << this.timestampsShift) | (this.dataCenterId << this.dataCenterIdShift) |
                (this.workerId << this.workerIdShift) | this.sequence;
    }

    private long nextMills(long lastTimestamp) {
        long timestamp = System.currentTimeMillis();
        // 如果当前时刻的时间戳 <= 上一次生成id的时间戳，就重新生成当前时间戳
        // 即确保当前时刻的时间戳，与上一次的时间戳不会重复
        while (timestamp <= lastTimestamp) {
            timestamp = System.currentTimeMillis();
        }
        return timestamp;
    }
}
